var visitor = {};
//Define angular app
var app = angular.module('TaskManager', []);

var canAdd = true;

//controllers
app.controller('taskController', ['$scope', function ($scope) {
    $scope.today = new Date();
    $scope.newTaskContent = null;
    $scope.newTaskName = null;
    $scope.newTask = null;
    $scope.newTaskDate = null;
    $scope.categories = [
        { name: 'Personal' },
        { name: 'Work' },
        { name: 'School' },
        { name: 'Cleaning' },
        { name: 'Other' }
    ];
    $scope.newTaskCategory = $scope.categories;
    $scope.init = function () { };

    $(document).ready(function () {
        var ic = new InformationController();
        var iv = new InformationValidator();

        $scope.addNew = function () {
            var taskItem;

            if (!canAdd) {
                alert("重复操作请刷新当前页面！");
                return;
            } else {
                canAdd = false;
            }

            if (!visitor.name) {
                alert("请选择一个文件");
                return;
            }

            if (iv.validateForm()) {
                if ($scope.newTaskDate == null || $scope.newTaskDate == '') {
                    taskItem = {
                        name: visitor.name,
                        description: $scope.newTask,
                        date: "No deadline",
                        category: $scope.newTaskCategory.name,
                    };
                } else {
                    taskItem = {
                        name: visitor.name,
                        description: $scope.newTask,
                        date: $scope.newTaskDate,
                        category: $scope.newTaskCategory.name,
                    };
                };

                $scope.newTask = '';
                $scope.newTaskDate = '';
                $scope.newTaskCategory = $scope.categories;

                ic.onUpdating();
                $.post('information-add', { taskItem: taskItem, content: visitor.content }, function (data, status) {
                    if (status == 'success') {
                        ic.onUpdateSuccess();
                    } else {
                        canAdd = true;
                        ic.onUpdateError();
                    }
                });
            }
        };
    });
}]);

//choose a file
$(document).ready(function () {

    $('#btn-information').attr('class', 'navbar-btn btn btn-default btn-active');

    var fileTypes = ['docx'];

    var parseFile = function (e) {
        e.preventDefault();
        notifyFileName();

        var file = e.target.files ? e.target.files[0] : e.dataTransfer.files[0];
        var size = Math.round(file.size / 1048576);
        var fileName = file.name.substring(file.name.lastIndexOf(".") + 1).toLowerCase();

        if (size > 3) {
            alert(["当前文件过大！(你当前的文件大小为", size, "MB)"].join(''));
            return;
        }

        if (fileTypes.indexOf(fileName) === -1) {
            alert(["请选择", fileTypes.join(','), "格式文件上传！(你当前的文件格式为", fileName].join(''));
            return;
        }

        notifyFileName(file);
        handleDrop(file);
    };

    var notifyFileName = function (file) {
        if (file) {
            $('#notify').html(file.name.match(/(.*).docx/)[1] + "  已经被选取");
        } else {
            $('#notify').html(["请选择（", fileTypes.join('/'), "）格式的文件"].join(''));
        }
    }
    var handleDrop = function (file) {
        var reader;
        var workbook;
        if (file) {
            reader = new FileReader;
            reader.onload = function (e) {
                visitor.content = reader.result;
                visitor.name = file.name.match(/(.*).docx/)[1];
            };
            reader.readAsDataURL(file);
        }
    }

    var target = document.querySelector('#target');

    target.addEventListener('dragenter', function (e) {
        e.preventDefault();
        this.classList.remove('hover');

    });
    target.addEventListener('dragleave', function (e) {
        e.preventDefault();
        this.classList.add('hover');
    });
    target.addEventListener('dragover', function (e) {
        e.preventDefault();
        this.classList.remove('hover');
    });
    target.addEventListener('drop', parseFile);

    var fileInput = document.createElement('input');

    fileInput.type = "file";
    fileInput.onchange = function (e) {
        parseFile(e);
    }
    $('#choose').click(function (e) {
        e.preventDefault();
        fileInput.click(e);
    });
});